//
//  ZLibCategoryListViewController.m
//  ZQLearn
//
//  Created by macfeel on 2019/4/25.
//  Copyright © 2019 macfeel. All rights reserved.
//

#import "ZLibCategoryListViewController.h"
#import "StoreCollectionViewCell.h"
#import "LibraryModel.h"
#import "ZBookMsgDetailVC.h"
#import "HomeModel.h"

@interface ZLibCategoryListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)UICollectionView *collectionView;


@property (nonatomic,strong)NSMutableArray *dataArray;


@property (nonatomic,assign)NSInteger currentIndex;

@end
#define kLineNumber 3
#define kBarHeight 40

///这个cellid 全局不能重复  所以建议写成宏的形式，而不是这种全局常量的形式
//NSString *const cellid = @"store";

#define cellIdentifier @"store"

@implementation ZLibCategoryListViewController


- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-ScreenHeightFlex) collectionViewLayout:[self flowLayout]];
        
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        
        [self registerCell];
        WeakStament(ws);
        _collectionView.mj_header = [CustomRefreshHeader headerWithRefreshingBlock:^{
            [ws refresh];
        }];
        _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [ws loadMore];
        }];
        _collectionView.backgroundColor = kWhiteColor;
    }
    return _collectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setItemWithTitle:self.ttitle?:@"" textColor:kNavigationTitleColor fontSize:18 itemType:center];
    self.currentIndex = 1;
    [self.view addSubview:self.collectionView];
    self.dataArray = [NSMutableArray array];
    [self loadData];
   
    YYLog(@"当前id：%@",self.cateId);
    // Do any additional setup after loading the view.
}
//-(void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    [UserModel shareInstance].isLib = YES;
//}
//- (void)viewDidDisappear:(BOOL)animated{
//    [super viewDidDisappear:animated];
//    [UserModel shareInstance].isLib = false;
//}
- (void)loadData{
    
    WeakStament(ws);
    if (self.currentIndex==1) {
        [self.dataArray removeAllObjects];
    }
    NSDictionary *dic;
    NSString *url;
    if ([self.isFlag isEqualToString:@"paint"]) {
        ///绘本馆
        url = kPaintBookListUrl;
        dic  =@{@"pageIndex":@(self.currentIndex),@"pageSize":@(24),@"PaintColumnInfo.id":self.cateId?:@""};
    }else if([self.isFlag isEqualToString:@"lib"]){
        ///图书馆首页进来的
        url = kLibraryCategoryListUrl;
        dic  =@{@"pageIndex":@(self.currentIndex),@"pageSize":@(24),@"libraryColumnInfo.id":self.cateId?:@""};
    }else{
        ///教材馆
        url = kTeachBookListUrl;
        dic  =@{@"pageIndex":@(self.currentIndex),@"pageSize":@(24),@"TeachMaterialColumnInfo.id":self.cateId?:@""};
        
    }
    
    [ZNetworkService getRequestWithBaseUrl:url setParameters:dic success:^(id result) {
        if ([result[@"errorCode"] integerValue]==0) {
            
            NSArray *arr = result[@"result"];
            
            for (NSDictionary *dict in arr) {
                LibraryModel *model = [LibraryModel mj_objectWithKeyValues:dict];
                NSString *url = [NSString stringWithFormat:@"%@%@",kPicServerUrl,model.bookInfo[@"firstPhoto"]];
                model.picUrl = url;
                model.ID = model.bookInfo[@"id"];
                model.isPaint = model.bookInfo[@"isPaint"];
                ///catelogType 1 word电子书  2 pdf 是绘本
                model.catelogType = model.bookInfo[@"catelogType"];
                model.price = model.bookInfo[@"price"];
                [ws.dataArray addObject:model];
            }
            [self.collectionView reloadData];
            [ws endRefresh];
            
//            /这个放的位置很重要  加载更多没有数据处理
            if (arr.count==0) {
                [ws noMoreData];
            }
        }else{
            [AFToast showText:result[@"errorMsg"]];
            [ws endRefresh];
        }
        YYLog(@"%@",result);
        
    } fail:^(NSError *error) {
        
        YYLog(@"%@",error);
        [ws endRefresh];
    } delegater:nil];
    
}

- (void)refresh{
    self.currentIndex=1;
    [self loadData];
}

- (void)loadMore{
    self.currentIndex++;
    [self loadData];
}

- (void)endRefresh{
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
}


///没有更多数据
- (void)noMoreData {
    [self.collectionView reloadData];
    [self.collectionView.mj_footer endRefreshingWithNoMoreData];
}

//流式布局
- (UICollectionViewFlowLayout *)flowLayout {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //整个 section 的四周边界的margin
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    ///45行代码和  ScreenWidth-4（minimumLineSpacing*2）形成中间的小横线
    layout.minimumLineSpacing = 2.f;
    layout.minimumInteritemSpacing = 0.f;
//    layout.headerReferenceSize = CGSizeMake(kScreenWidth, SectionHeaderHeight);
    layout.itemSize = CGSizeMake((ScreenWidth-4)/3, 200);
    
    return layout;
}


- (void)registerCell {
    
    [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([StoreCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:cellIdentifier];
    
    //最后一个有一个尾视图  到时候需要用到
    //    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headReuseID];
    
}



#pragma datasource
//-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
//    return 1;
//}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataArray.count;
}



-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    StoreCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    LibraryModel *model = self.dataArray[indexPath.row];
    [cell.headImg sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:nil];
    cell.nameLab.text  = model.name;
    cell.scoreLab.hidden = YES;
    return cell;
}


#pragma mark - delegate

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    LibraryModel *model = self.dataArray[indexPath.row];
    ZBookMsgDetailVC *detail = [ZBookMsgDetailVC new];
    MidModel *MModel = [MidModel new];
    MModel.name = model.name;
    MModel.ID = model.ID;
    MModel.isPaint = model.isPaint;
    MModel.catelogType = model.catelogType;
    MModel.price = model.price;
    YYLog(@"%@",model.price);
    MModel.picUrl = [NSString stringWithFormat:@"%@%@",kPicServerUrl,model.bookInfo[@"photo"]];
    
    detail.MModel = MModel;
    [self.navigationController pushViewController:detail animated:YES];
}


//cell尺寸
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//
//    CGFloat width=ScreenWidth/kLineNumber;
//    return CGSizeMake(width, width*1.2);
//}

///section header 尺寸
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeMake(ScreenWidth, SectionHeaderHeight-20);
//}


-(void)dealloc{
    
    [UserModel shareInstance].isLib = false;
    
}

@end
